package com.twu.biblioteca.model;

import com.twu.biblioteca.controller.Book;
import com.twu.biblioteca.controller.User;

import java.util.ArrayList;

/**
 * Created by ggoulart on 9/29/14.
 */
public class BookDAO {

    private ArrayList<Book> availableBooks = new ArrayList<Book>();
    private ArrayList<UnavailableBook> checkoutBooks = new ArrayList<UnavailableBook>();

    private class UnavailableBook {
        private Book book;
        private User user;

        protected UnavailableBook(Book book, User user) {
            this.book = book;
            this.user = user;
        }

        protected Book getBook() {
            return book;
        }

        protected User getUser() {
            return user;
        }
    }

    public BookDAO() {
        availableBooks.add(new Book("Head First Java", "Bert Bates and Kathy Sierra", 2004));
        availableBooks.add(new Book("TDD by Example", "Kent Beck", 2002));
        //checkoutBooks.add(new Book("Eloquent JavaScript", "Marijn Haverbeke", 2011));
    }

    public Book findBookByName(String bookName) throws Exception {
        for (Book book : availableBooks) {
            if (bookName.equals(book.getName()))
                return book;
        }
        for (UnavailableBook unavailableBook : checkoutBooks) {
            if(bookName.equals(unavailableBook.getBook().getName()))
                return unavailableBook.getBook();
        }
        throw new Exception("Book doesn't exists.");
    }

    public ArrayList<Book> getAvailableBooks() {
        return availableBooks;
    }

    public boolean addAvailableBook(Book book) {
        return availableBooks.add(book);
    }

    public boolean removeAvailableBook(Book book) {
        return availableBooks.remove(book);
    }

    public boolean addCheckoutBooks(Book book, User user) {
        return checkoutBooks.add(new UnavailableBook(book, user));
    }

    public boolean removeCheckoutBooks(Book book) throws Exception {
        return checkoutBooks.remove(getUnavailableBook(book));
    }

    private UnavailableBook getUnavailableBook(Book book) throws Exception {
        for(UnavailableBook unavailableBook : checkoutBooks) {
            if(unavailableBook.getBook().equals(book))
                return unavailableBook;
        }
        throw new Exception("Book doesn't exists.");
    }
}
